<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="计划单编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="code"
            >
              <a-input v-model="model.code" disabled placeholder="请输入计划单编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="开始日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="startTime"
            >
              <j-date
                placeholder="请选择开始日期"
                v-model="model.startTime"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="结束日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="endTime"
            >
              <j-date
                placeholder="请选择结束日期"
                v-model="model.endTime"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <j-select-depart disabled v-model="model.sysOrgCode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="计划明细" :key="refKeys[0]" :forceRender="true">
        <div class="table-operator">
          <!-- 暂时不允许添加后期需要再打开 -->
          <!-- <a-button @click="addMateriel" type="primary" icon="plus" :disabled="formDisabled">新增</a-button> -->
          <a-button @click="copyRow" type="primary" icon="copy" :disabled="formDisabled">复制</a-button>
        </div>
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussMaterialProcurementPlanDetailTable.loading"
          :columns="bussMaterialProcurementPlanDetailTable.columns"
          :dataSource="bussMaterialProcurementPlanDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="false"
          :rowSelection="true"
          :toolbar="false"
          rowSelectionType="radio"
          @cell-click="cellClickEvent"
          @selectRowChange="selectRowChange"
        >
          <template v-slot:supplierId="props">
            <tsl-mat-supplier
              v-model="props.value"
              :isDisabled="formDisabled"
              :rowData="props"
              @handlerOk="supplierOk"
            ></tsl-mat-supplier>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>

    <erp-goods-list-model ref="selectGoodsList" category="4" @goodsOk="goodsOk" checkval="radio"></erp-goods-list-model>
  </a-spin>
</template>

<script>
import { getAction, postAction, putAction, httpAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import ErpGoodsSupplierListModal from '@comp/base/modal/ErpGoodsSupplierListModal'
import BussApplicationListModal from '@comp/base/modal/BussApplicationListModal'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import store from '@/store'
import moment from 'dayjs'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import TslMatSupplier from '@comp/tsl/cell/TslMatSupplier.vue'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'BussMaterialProcurementPlanForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    BussApplicationListModal,
    JSelectDepart,
    ErpGoodsListModel,
    TslMatSupplier,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      categoryOptions: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      category: '1',
      applicationId: '1',
      row: {},
      model: {
        code: '',
        applicationId: '',
        submissionDate: '',
      },
      curRow: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        startTime: [{ required: true, message: '请选择开始日期!' }],
        endTime: [{ required: true, message: '请选择结束日期!' }],
      },
      refKeys: ['bussMaterialProcurementPlanDetail'],
      tableKeys: ['bussMaterialProcurementPlanDetail'],
      activeKey: 'bussMaterialProcurementPlanDetail',
      // 原料采购计划单明细
      bussMaterialProcurementPlanDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '行号',
            key: 'seq',
            // type: JVXETypes.input,
            width: '50px',
            defaultValue: '',
          },
          {
            title: '原料编号',
            key: 'materialCode',
            // type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '原料名称',
            key: 'materialName',
            // type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '供货单位',
            key: 'supplierName',
            width: '180px',
            type: JVXETypes.slot,
            slotName: 'supplierId',
            // 使用内置的下拉选项组件
            // widget: 'select',
            // // 下拉选项的数据
            // options: []
          },
          {
            title: '现有库存',
            key: 'number',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '安全库存',
            key: 'stockQuantity',
            // type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '计划采购',
            key: 'num',
            type: JVXETypes.input,
            width: '120px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '单位',
            key: 'meUnit',
            width: '80px',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '到货日期',
            key: 'arrivalDate',
            // type: JVXETypes.input,
            width: '200px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
        ],
      },
      url: {
        add: '/plan/bussMaterialProcurementPlan/add',
        edit: '/plan/bussMaterialProcurementPlan/edit',
        queryById: '/plan/bussMaterialProcurementPlan/queryById',
        bussMaterialProcurementPlanDetail: {
          list: '/plan/bussMaterialProcurementPlan/queryBussMaterialProcurementPlanDetailByMainId',
          applicationDetail: '/plan/bussMaterialProcurementPlan/applicationDetail',
          applicationDetailById: '/plan/bussMaterialProcurementPlan/applicationDetailById',
        },
      },
    }
  },

  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      console.log(this.model)
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/procurement_plan_code'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    goodsOk(data) {
      let detail = {}
      detail.materialName = data.name
      detail.materialCode = data.code
      detail.materialId = data.id
      detail.spec = data.noneSpec
      detail.unit = data.meUnit_dictText
      this.bussMaterialProcurementPlanDetailTable.dataSource.push(detail)
    },
    addMateriel() {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    cellClickEvent({ row, column }) {
      // if (column.property === 'supplierName') {
      //   this.row = row
      //   this.category = row.materialId
      //   console.log(this.category)
      //   this.$refs.selectSuppliersList.add()
      //   this.$refs.selectSuppliersList.title = '选择供应商'
      //   this.$refs.selectSuppliersList.disableSubmit = false
      // }
    },
    supplierOk({ row, data, value }) {
      this.$set(this.row, 'supplierName', data.name)
      this.$set(this.row, 'supplierId', data.id)
      row.supplierId = data.id
      row.supplierName = data.name
    },
    addBefore() {
      this.bussMaterialProcurementPlanDetailTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    add() {
      this.getSequenceNum()
      //显示请购单明细
      this.bussMaterialProcurementPlanDetailTable.dataSource = []
      let tempList = store.getters.materialApplicationDetailList
      this.model.applicationId = ''
      if (tempList.length > 0) {
        console.log(tempList)
        tempList.forEach((row, index) => {
          this.bussMaterialProcurementPlanDetailTable.dataSource.push({
            applicationDetailId: row.detailId,
            materialId: row.materialId,
            materialCode: row.materialCode,
            materialName: row.materialName,
            spec: row.spec,
            num: row.num,
            arrivalDate: row.arrivalDate,
            stockQuantity: row.stockSafeQuantity,
            number: '0',
            meUnit: row.unit,
            seq: index + 1,
          })
        })

        this.model.applicationId = tempList[0].id
      }
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.editAfter()
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        //todo 暂时没有供货商关联
        this.requestSubTableData(
          this.url.bussMaterialProcurementPlanDetail.list,
          params,
          this.bussMaterialProcurementPlanDetailTable
        )
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        details: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    selectRowChange({ type, action, selectedRows, $event }) {
      this.curRow = selectedRows
    },
    copyRow() {
      if (this.curRow && this.curRow.length > 0) {
        let data = {}
        Object.assign(data, this.curRow[0])
        data.id = data.id + 'aaa'
        data.seq = this.bussMaterialProcurementPlanDetailTable.dataSource.length + 1
        this.bussMaterialProcurementPlanDetailTable.dataSource.push(data)
      } else {
        this.$message.warn('请选择一条记录复制！')
        return
      }
    },
    //提交表单数据
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true

      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            //241119修改提交时还要判断是否直接进入审批流
            if (!this.model.id) {
              this.model.dataId = res.message
              this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'MaterialProcurementPlanService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
  },
}
</script>

<style scoped></style>
